package com.hermit.qmst.UI.main;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.hermit.qmst.MainActivity;
import com.hermit.qmst.R;
import com.hermit.qmst.UI.activity.CallingActivity;
import com.hermit.qmst.UI.activity.SelectCallActivity;
import com.hermit.qmst.UI.widget.AlphaView;
import com.hermit.qmst.adapter.ContactAdapter;
import com.hermit.qmst.adapter.ContactsAdapter;
import com.hermit.qmst.mode.ContactInfo;
import com.hermit.qmst.tools.Common;
import com.hermit.qmst.tools.Log;
import com.hermit.qmst.tools.Preferences;
import com.hermit.qmst.tools.SipCallHelp;
import com.hermit.qmst.tools.Utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public class ContactsFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>,View.OnClickListener{

    private String TAG="ContactFragment";
    private ListView mListView;
    private ContactsAdapter mContactAdapter;
    private ArrayList<ContactInfo> mContactInfoList = new ArrayList<ContactInfo>();
    private LoaderManager mLoaderManager;
    private int CONTACT_LOADER_MANAGER_ID = 1000;
    private int mPosition = 0;//listview位置
    private int mPreClickPosition = -1;//上一个选中的位置
    private View view;
    private TextView mTitle, mAddContact;
    private ImageView mTitleLeft;
    private EditText metSearch;
    private ImageView mivSearchDel;
    private ArrayList<ContactInfo> mSearchContactInfoList = new ArrayList<ContactInfo>();
    private AlphaView mAlphaView;
    private HashMap<String,Integer> mAlphaIndex = new HashMap<String,Integer>();//每组第一个联系人 字母/位置 键对值
    private TextView mtvShowAlpha;
    private Handler mHandler = new Handler();
    private ShowAlphaThread mshowAlphaThread;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mshowAlphaThread = new ShowAlphaThread();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        if (view == null){
            view = inflater.inflate(R.layout.activity_tab_contact,null);
        }else {
            ViewGroup vp =  (ViewGroup)view.getRootView();
            vp.removeView(view);

        }

        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (mListView == null){
            initView();
            mLoaderManager = getLoaderManager();
            mLoaderManager.initLoader(CONTACT_LOADER_MANAGER_ID,null,this);
            Log.i("ContactFragment","onViewCreated",true);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        mHandler.removeCallbacks(mshowAlphaThread);
        ((WindowManager)getActivity().getSystemService(Context.WINDOW_SERVICE)).removeViewImmediate(mtvShowAlpha);
    }

    private void initView(){
        MainActivity.getInstance().mTabbar.setVisibility(View.GONE);
        mListView = (ListView)getActivity().findViewById(R.id.lv_contact);
        mtvShowAlpha = (TextView)LayoutInflater.from(getActivity()).inflate(R.layout.widget_alpha,null);
        mtvShowAlpha.setVisibility(View.GONE);
        //把mtvShowAlpha添加到窗口
        WindowManager.LayoutParams params = new WindowManager.LayoutParams(-2,-2,2,24,-3);
        ((WindowManager)getActivity().getSystemService(Context.WINDOW_SERVICE)).addView(mtvShowAlpha,params);


        metSearch = (EditText)getActivity().findViewById(R.id.et_search);
        mivSearchDel = (ImageView)getActivity().findViewById(R.id.bt_search_del);
        mivSearchDel.setOnClickListener(this);

        mAlphaView = (AlphaView)getActivity().findViewById(R.id.alpha);

        initListener();
    }

    private void initListener(){
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                //mSearchContactInfoList.size() > 0 说明显示搜索联系人
//                if (mSearchContactInfoList.size() > 0){
//
                    ContactInfo info = (ContactInfo)parent.getAdapter().getItem(position);
                    Common.mCallAera = info.getPhoneAera();
                    Common.mCallName = info.getName();
                    Common.mCallPhone = info.getPhone1();
//
                    Preferences preferences = new Preferences(getActivity());
                    String type = preferences.getPreferenceStringValue(Preferences.CALL_WAY);
                    if (type.equals("0")) {
                        Intent intent = new Intent(getActivity(), CallingActivity.class);
                        startActivity(intent);
                    }else if (type.equals("1")){
                        SipCallHelp.placeCallWithOption(null,getActivity(),info.getPhone1());
                    }else if (type.equals("2")){

                        if (Common.checkWIFI(getActivity())){
                            SipCallHelp.placeCallWithOption(null, getActivity(), info.getPhone1());
                        }else {
                            Intent intent = new Intent(getActivity(), CallingActivity.class);
                            startActivity(intent);
                        }
                    }else {

                        Intent intent = new Intent(getActivity(), SelectCallActivity.class);
                        startActivity(intent);
                    }
//                }else {
//                    //隐藏上一个显示的打电话图标
//                    if (mPreClickPosition >= 0 && mPreClickPosition != position){
//                        ContactInfo preInfo = (ContactInfo)parent.getAdapter().getItem(mPreClickPosition);
//                        if (preInfo.isShowCallItem()){
//                            preInfo.setShowCallItem(false);
//                        }
//                    }
//
//                    ContactInfo info = (ContactInfo)parent.getAdapter().getItem(position);
//                    info.setShowCallItem(!info.isShowCallItem());
//                    //如果打电话图标显示，则记录位置
//                    if (info.isShowCallItem()){
//                        mPreClickPosition = position;
//                    }else {
//                        mPreClickPosition = -1;
//                    }
//
//                    mContactAdapter.notifyDataSetChanged();
//                }
            }
        });

        metSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0){
                    mivSearchDel.setVisibility(View.VISIBLE);
                    queryContact(s.toString());
                    ContactAdapter adapter = new ContactAdapter(getActivity(),mSearchContactInfoList,false);
                    mListView.setAdapter(adapter);

                }else {
                    mivSearchDel.setVisibility(View.GONE);
                    mListView.setAdapter(mContactAdapter);
                    mSearchContactInfoList.clear();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        //显示选中的字母
        mAlphaView.setOnTouchingAlphaChangedListener(new AlphaView.OnTouchingAlphaChangedListener() {
            @Override
            public void onTouchingAlphaChanged(String alpha) {

                if (mAlphaIndex.size() == 0) {
                    return;
                }
                Integer index = mAlphaIndex.get(alpha);
                mtvShowAlpha.setText(alpha);

                mtvShowAlpha.setVisibility(View.VISIBLE);
                mHandler.removeCallbacks(mshowAlphaThread);
                mHandler.postDelayed(mshowAlphaThread, 1500L);
                Log.i(TAG,"显示选中的字母:"+index,true);
                if (index != null) {
                    mListView.setSelection(index.intValue());
                }

            }
        });
    }

    //显示字母线程
    private class ShowAlphaThread implements Runnable{

        @Override
        public void run() {
            mtvShowAlpha.setVisibility(View.GONE);
        }
    }

    private void getConatctAlpha(List<ContactInfo> list){

        for (int i = 0; i < list.size(); i++){
            ContactInfo info = list.get(i);
            String alpha = Utils.getFirstLetter(info.getSortKey());
            if (i == 0){
                mAlphaIndex.put(alpha,Integer.valueOf(i));
            }else {
                ContactInfo preInfo = list.get(i - 1);
                String preAlpha = Utils.getFirstLetter(preInfo.getSortKey());
                if (!preAlpha.equals(alpha)){
                    mAlphaIndex.put(alpha, Integer.valueOf(i));
                }
            }
        }


    }

    //搜索联系人

    private void queryContact(String input){

        mSearchContactInfoList.clear();

        for (int i = 0;i < mContactInfoList.size(); i++) {
            ContactInfo info = mContactInfoList.get(i);

            String name = info.getName();
            String phone = info.getPhone1();
            String pinYin = info.getPinYin().toLowerCase();

            //判断首字母
            boolean b = true;
            String[] allPinyin = pinYin.split(" ");

            if (input.length() <= allPinyin.length) {
                for (int j = 0; j < input.length(); j++) {
                    String inputAlpha = input.substring(j, j + 1);
                    String nameAlpha = Utils.getFirstLetter(allPinyin[j]);
                    if (!inputAlpha.toUpperCase().equals(nameAlpha.toUpperCase())) {
                        b = false;
                    }

                }
            } else {

                b = false;
            }

            if (name.contains(input) || phone.contains(input) || pinYin.contains(input) || b) {
                mSearchContactInfoList.add(info);
            }


        }
    }

    @Override
    public Loader onCreateLoader(int id, Bundle args) {
        Log.i("onCreateLoader", "id = " + id, true);
        CursorLoader loader = new CursorLoader(getActivity());
        //设置查询路径
        loader.setUri(ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
        //设置查询的列
        loader.setProjection(new String[]{ ContactsContract.CommonDataKinds.Phone._ID, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.DATA1, ContactsContract.CommonDataKinds.Phone.SORT_KEY_PRIMARY, ContactsContract.CommonDataKinds.Phone.PHOTO_ID, ContactsContract.CommonDataKinds.Phone.CONTACT_ID });
        //设置查询条件 按时间顺序查询
        loader.setSortOrder("sort_key COLLATE LOCALIZED asc");
        return loader;
    }

    @Override
    public void onLoadFinished(Loader loader, Cursor cursor) {

        boolean c = false;

        while (cursor.moveToNext()){

            if (!c){
                mContactInfoList.clear();
                c = true;
            }

            String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            if (name == null){
                name = "";
            }

            String phone = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA1));
            if (phone == null || phone.length() < 11){
                continue;
            }

            phone = Utils.analysePhoneNumber(phone);

            String sortKey = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.SORT_KEY_PRIMARY));

            ContactInfo info = new ContactInfo();
            info.setName(name);
            info.setPhone1(phone);
            info.setPinYin(Utils.getPinYin(name));
            info.setSortKey(sortKey);

            mContactInfoList.add(info);
        }

        if (c && mContactInfoList.size() > 0){
            mContactAdapter = new ContactsAdapter(getActivity(),mContactInfoList);
            mListView.setAdapter(mContactAdapter);
            getConatctAlpha(mContactInfoList);
        }

    }

    @Override
    public void onLoaderReset(Loader loader) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_title_right:

                Intent intent = new Intent(Intent.ACTION_INSERT,ContactsContract.Contacts.CONTENT_URI);
                getActivity().startActivity(intent);
                break;
            case R.id.bt_search_del:
                metSearch.setText("");
                break;
            default:
                break;
        }
    }
}
